package com.haihui.platform.utils;

import java.security.Security;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

/*
 * 3DES加密
 */
public class TripleDES {

	private static final String Algorithm = "DESede";
	
	private static final String KEY = "IkMjzVOjJpqQUBYuFmmpjkgl";
	
	static{
		Security.addProvider(new com.sun.crypto.provider.SunJCE());
	}
	
	/**
	 * 生成密文字节
	 * @param keybyte
	 * @param src
	 */
	public static byte[] encryptMode(byte[] keybyte, byte[] src) {  
        try {  
            // 生成密钥  
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);  
  
            // 加密  
            Cipher c1 = Cipher.getInstance(Algorithm);  
            c1.init(Cipher.ENCRYPT_MODE, deskey);  
            return c1.doFinal(src);  
        } catch (java.security.NoSuchAlgorithmException e1) {  
            e1.printStackTrace();  
        } catch (javax.crypto.NoSuchPaddingException e2) {  
            e2.printStackTrace();  
        } catch (java.lang.Exception e3) {
            e3.printStackTrace();  
        }  
        return null;  
    }
	
	/**
	 * 生成明文字节
	 * @param keybyte
	 * @param src
	 */
	public static byte[] decryptMode(byte[] keybyte, byte[] src) {  
        try {  
            // 生成密钥  
            SecretKey deskey = new SecretKeySpec(keybyte, Algorithm);  
  
            // 解密  
            Cipher c1 = Cipher.getInstance(Algorithm);  
            c1.init(Cipher.DECRYPT_MODE, deskey);  
            return c1.doFinal(src);  
        } catch (java.security.NoSuchAlgorithmException e1) {  
            e1.printStackTrace();  
        } catch (javax.crypto.NoSuchPaddingException e2) {  
            e2.printStackTrace();  
        } catch (java.lang.Exception e3) {  
            e3.printStackTrace();  
        }  
        return null;  
    }
	
	/**
	 * 明文转密文
	 * @param text
	 * @return
	 */
	public static String getCiphert(String text){
		byte[] keyBytes = KEY.getBytes();
		byte[] encoded = encryptMode(keyBytes, text.getBytes());
		String ciphert = Base64.encodeBase64String(encoded);
		return ciphert;
	}
	
	/**
	 * 密文转明文
	 * @param text
	 */
	public static String getClearText(String text){
		byte[] keyBytes = KEY.getBytes();
		byte[] srcBytes = decryptMode(keyBytes, Base64.decodeBase64(text));
		return new String(srcBytes);
	}
	
	//测试
	public static void main(String[]args){
		System.out.println(getCiphert("123"));
	}
	
}
